<?php
namespace Modules\ApiV2\Controllers;
use App\Models\Coupon;
use App\Models\MobileRecharge;
use App\Models\OilCard;
use App\Models\Pay;
use App\Models\Recharge;
use App\Models\RechargeOrder;
use App\Models\User;
use App\Models\UserCoupon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\Service\Logic\CouponLogic;
use Modules\Service\Logic\MobileFareOrderLogic;
use Modules\Service\Logic\OilcardOrderLogic;
use Modules\Service\Logic\RechargeLogic;
use Modules\Token\Facades\Token;

class RechargeController extends BaseController{

    /*********************油卡充值*********************/

    //油卡直充
    public function oilRechargeMeal(){
        //获取直冲套餐
        $meal = config('recharge.meal');
        return self::success($meal);
    }

    //获取我的油卡和优惠券信息
    public function getUserOilAndCoupon(){
        try {
            //获取用户Id
            $userId = Token::data("id");
            //获取用户Id
            $userData = User::find($userId);
            if (!$userData) return self::fail(1014, "用户不存在");
            //查询我的油卡
            $oidData = OilCard::where("user_id", $userId)->select("id", "card_no", "type")->get();

            return self::success(["user_oil"=>$oidData]);
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统错误");
        }
    }

    //油卡充值套餐
    public function rechargeMeal(){
        //查询充值套餐
        $data = Recharge::select("id","title","discount","max_amount","min_amount","only_first","months","tag","sell_num","selected","img_url","amount")->orderBy('months','asc')->get();
        return self::success($data);
    }

    //油卡充值明细
    public function rechargeDetail(Request $request){
        try{
            //获取参数
            $amount = $request->input("amount",false);
            $rechargeId = $request->input("recharge_id",false);
            $channel = $request->input("channel",false);

            if (0 == $rechargeId) {
                return self::success([['num' => 1, 'date' => date('Y-m-d'), 'amount' => $amount]]);
            }

            //验证参数
            if (!$amount)return self::fail(1003,"缺少必要参数:amount");
            if (!$rechargeId)return self::fail(1003,"缺少必要参数:recharge_id");
            if (!$channel)return self::fail(1003,"缺少必要参数:channel");
            //查询套餐
            if ($channel=='oil_recharge') {
                $rechargeData = Recharge::find($rechargeId);
            }else{
                $rechargeData = MobileRecharge::find($rechargeId);
            }
            if (!$rechargeData)return self::fail(1013,"套餐无效,请重新选择");
            //定义数组
            $detail = [];
            //当前日期
            $today = date('d');
            for ($i = 0; $i < $rechargeData->months; $i++) {
                //获取当前月第一天
                $oneDay = date('Y-m-01', strtotime("+{$i} months"));
                //获取当前月最后一天
                $lastDay = date('d', strtotime("{$oneDay}+1 month -1 day"));
                if ($today <= $lastDay) {
                    if ($rechargeData->months==1){
                        $date = date('Y-m',strtotime("+1 months")). '-' . $today;
                    }else {
                        $date = date('Y-m', strtotime("+{$i} months")) . '-' . $today;
                    }
                } else {
                    if ($rechargeData->months==1) {
                        $date = date('Y-m',strtotime("+1 months")). '-' . $today;
                    }else{
                        $date = date('Y-m', strtotime("+{$i} months")) . '-' . $lastDay;
                    }
                }
                $detail[] = ["num" => $i + 1, "date" => $date, "amount" => $amount];
            }
            return self::success($detail);
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统错误");
        }
    }

    //充值并首次支付
    public function rechargeOrderAndPay(Request $request){
        try {
            //获取用户Id
            $userId = Token::data("id");
            //查询用户数据
            $userData = User::find($userId);
            if (!$userData)return self::fail(1014,"用户不存在");
            //获取充值id
            $rechargeId = $request->input("recharge_id", false);//套餐ID
            $couponId = $request->input("coupon_id", false);//优惠券Id
            $payType = $request->input("pay_type", 'weixin');//支付方式
            $rechargeAmount = $request->input("amount", false);//充值金额
            $oilCardId = $request->input("oil_card_id", false);//油卡ID
            $mobile = $request->input("mobile",false);//手机号
            $openid = $request->input("openid",false);//微信支付openid
            $platform = $request->header("app-platform",'ios');
            $version = $request->header("app-version",'1.1.3');
            //验证参数
            if ($payType=='weixin'){
                if (!$openid && !$userData->open_id)return self::fail(1003,"网络异常!");
            }
            if (!$oilCardId && !$mobile)return self::fail(1003,"请选择油卡");
            if (!$rechargeAmount)return self::fail(1003,"请选择充值金额");
            if (!$payType || ($payType!='weixin' && $payType!='alipay' && $payType!='weixin_app'))return self::fail(1003,"缺少必要参数:pay_type");
            if ($oilCardId && !$mobile){
                $type = "oil_recharge";
            }elseif($mobile && !$oilCardId){
                $type = "mobile_recharge";
            }else{
                return self::fail(1029,"充值类型异常");
            }
            return OilcardOrderLogic::oilOrderAndPay($oilCardId,$mobile,$type,$openid,$rechargeId,$payType,$rechargeAmount,$couponId,$userData,$version,$platform);
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500);
        }
    }

    //再次支付
    public function rechargeOrderAgainPay(Request $request){
        //获取充值订单Id
        $id = $request->input("order_id");
        //付款方式
        $payType = $request->input('pay_type',false);
        //类型
        $channel = $request->input("channel", false);
        $openid = $request->input("openid",false);
        //验证参数
        if (!$id)return self::fail(1003,"缺少必要参数:id");
        if (!$payType)return self::fail(1003,"缺少必要参数:payment_method");
        if (!$channel || ($channel!='oil_recharge' && $channel!='mobile_recharge'))return self::fail(1003,"缺少必要参数:channel");
        if ($payType=='weixin' && !$openid)return self::fail(1003,"缺少必要参数:openid");


        return OilcardOrderLogic::oilOrderAgainPay($id,$payType,$channel,$openid);
    }

    /**********************优惠券**********************/

    //根据金额查询可用优惠券
    public function usableCoupon(Request $request){
        try {
            //获取用户Id
            $userId = Token::data('id');
            //查询用户
            $userData = User::find($userId);
            if (!$userData) return self::fail(1014, "用户不存在");
            //接收参数
            $rechargeAmount = $request->input("amount", false);
            $rechargeId = $request->input("recharge_id", false);
            $channel = $request->input("channel",false);
            //验证参数
            if (!$rechargeAmount) return self::fail(1003, "缺少必要参数:amount");
            //if (!$channel)return self::fail(1003,"缺少必要参数:channel");
            //操作
            return CouponLogic::userCoupon($userData->id,$rechargeAmount,$rechargeId,$channel);
        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统异常");
        }
    }

    //优惠券
    public function userCoupons(Request $request){
        try{
            //获取用户信息
            $userId = Token::data('id');
            $userData = User::find($userId);
            if (!$userData)return self::fail(1014,"用户不存在");
            //接收参数
            $channel = $request->input("channel",false);
            //效验参数
            if (!$channel){
                //查询我的全部优惠券
                $couponData = UserCoupon::where("user_id", $userId)->where("status",1)->count();
            }else{
                //根据使用渠道查询优惠券
                $couponData = UserCoupon::where("user_id", $userId)->where("channel",$channel)->where("status",1)->count();
            }
            return self::success(["coupon_num"=>$couponData]);

        }catch (\Exception $e){
            Log::error($e);
            return self::fail(500,"系统错误");
        }
    }

    /**********************话费充值********************/

    //话费直冲
    public function mobileRechargeMeal(){
        //获取充值套餐
        $meal = config('recharge.mobile');
        return self::success($meal);
    }

    //话费充值套餐
    public function mobileRecharges(){
        //查询话费充值套餐
        $mobileData = MobileRecharge::select('id','title','discount',"max_amount","min_amount",'only_first','months','tag','img_url',"sell_num","selected")->where('is_show',1)->get();
        return self::success($mobileData);
    }


//    //话费充值下单并首次支付
//    public function mobileRechargeOrderAndPay(Request $request){
//        try{
//            //获取用户Id
//            $userId = Token::data("id");
//            //查询用户数据
//            $userData = User::find($userId);
//            if (!$userData)return self::fail(1014,"用户不存在");
//            //获取充值id
//            $rechargeId = $request->input("recharge_id", false);//套餐ID
//            $couponId = $request->input("coupon_id", false);//优惠券Id
//            $payType = $request->input("pay_type", 'weixin');//支付方式
//            $rechargeAmount = $request->input("amount", false);//充值金额
//            $mobile = $request->input("mobile", false);//手机号
//            $openid = $request->input("openid",false);//微信支付openid
//
//            //验证参数
//            if ($payType=='weixin'){
//                if (!$openid && !$userData->open_id)return self::fail(1003,"缺少必要参数:openid");
//            }
//            if (!$rechargeAmount)return self::fail(1003,"缺少必要参数:recharge_amount");
//            if (!$mobile) return self::fail(1003, "缺少必要参数:mobile");
//            if (!$payType || ($payType!='weixin' && $payType!='alipay'))return self::fail(1003,"缺少必要参数:pay_type");
//
//            return MobileFareOrderLogic::mobileOrderAndPay($mobile,$openid,$rechargeId,$payType,$rechargeAmount,$couponId,$userData);
//        }catch (\Exception $e){
//            Log::error($e);
//            return self::fail(500,"系统错误");
//        }
//    }
//
//    //话费充值下单再次支付
//    public function mobileRechargeOrderAgainPay(Request $request){
//        //获取充值订单Id
//        $id = $request->input("id");
//        //付款方式
//        $payType = $request->input('pay_type');
//        //验证参数
//        if (!$id)return self::fail(1003,"缺少必要参数:id");
//        if (!$payType)return self::fail(1003,"确实必要参数:payment_method");
//
//        return MobileFareOrderLogic::mobileOrderAgainPay($id,$payType);
//    }


    /************************充值订单*************************/

    //充值订单列表
    public function rechargeOrderList(Request $request){
        $userId = Token::data("id");
        $type = $request->input("type",'oil_recharge');
        $page = $request->input("page",1);
        $size = $request->input("limit",20);
        $status = $request->input("status",'all');
        if ($type!='oil_recharge' && $type!='mobile_recharge')return self::fail(1003,"参数值错误:type");
        return RechargeLogic::rechargeOrderLit($userId,$type,$page,$size,$status);
    }

    //订单详情
    public function rechargeOrderDetail(Request $request){
        $orderId = $request->input("order_id");
        $type = $request->input("type",'oil_recharge');
        if (!$orderId)return self::fail("缺少必要参数:order_id");
        if ($type!='oil_recharge' && $type!='mobile_recharge')return self::fail(1003,"参数值错误:type");
        return RechargeLogic::recgargeOrderDetail($orderId,$type);
    }

    //取消订单
    public function rechargeOrderClose(Request $request){
        $orderId = $request->input("order_id",false);
        $channel = $request->input("channel",'oil_recharge');
        $type = $request->input("type","close");
        if (!$orderId)return self::fail(1003,"缺少必要参数:order_id");
        if ($channel!='oil_recharge' && $channel!='mobile_recharge')return self::fail(1003,"参数值错误:type");
        return RechargeLogic::rechargeOrderClose($orderId,$channel,$type);
    }
}